<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\Activity;
use app\model\Expense;
use think\facade\Db;

/**
 * @extends Service<ExpenseService>
 */
class ExpenseService extends Service
{


    public function save($data, $user_id, $expense_id = null)
    {
        Db::startTrans();
        try {
            if (empty($expense_id)) {
                Expense::create([
                    'user_id' => $user_id,
                    'activity_id' => $data['activity_id'],
                    'title' => $data['title'],
                    'image' => $data['image'],
                    'category' => $data['category'],
                    'expense_time' => $data['expense_time'],
                    'apply_time' => $data['apply_time'],
                    'money' => $data['money'],
                    'status' => 1,
                ]);
            } else {
                $info = Expense::where('expense_id', $expense_id)->find();
                if (empty($info)) {
                    throw new \Exception('数据不存在');
                }
                $info->save([
                    'user_id' => $user_id,
                    'activity_id' => $data['activity_id'],
                    'title' => $data['title'],
                    'image' => $data['image'],
                    'category' => $data['category'],
                    'expense_time' => $data['expense_time'],
                    'apply_time' => $data['apply_time'],
                    'money' => $data['money'],
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }

        return true;
    }

    public function info($expense_id)
    {
        $info = Expense::where('expense_id', $expense_id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }

        return $info->toArray();
    }
}